/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2024, USTC
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of USTC nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Xinsheng Tang */
#include "pilz_tutorial/pilz_base.h"
#include "pilz_tutorial/robot_exception.h"

void writeFile(std::string file_path, std::string name,
               std::vector<double> joints) {
  Json::Reader jsonreader;
  Json::Value root;
  Json::StyledWriter writer;
  std::ifstream ifile(file_path, std::ios::binary);
  if (jsonreader.parse(ifile, root)) {
    int i;
    for (i = 0; i < root["joints"].size(); ++i) {
      if (root["joints"][i]["name"].asString() == name) break;
    }
    Json::Value joint;
    joint["name"] = Json::Value(name);
    for (int j = 0; j < 6; ++j) {
      joint["value"][j] = Json::Value(joints[j]);
    }
    if (i < root["joints"].size()) {
      root["joints"][i] = joint;
      std::cout << file_path << "\n修改关节角:\n"
                << joint.toStyledString() << std::endl;
    } else {
      root["joints"].append(joint);
      std::cout << file_path << "\n添加关节角:\n"
                << joint.toStyledString() << std::endl;
    }
    ifile.close();
    std::ofstream ofile(file_path, std::ios::binary);
    ofile << writer.write(root);
    ofile.close();
  }
}

int main(int argc, char **argv) {
  ros::init(argc, argv, "pilz_record");
  setlocale(LC_ALL, "");
  ros::NodeHandle nh;
  moveit::planning_interface::MoveGroupInterfacePtr mgptr =
      std::make_shared<moveit::planning_interface::MoveGroupInterface>(
          "manipulator");
  manipulator ur5e(nh, mgptr);
  ros::AsyncSpinner spinner(10);
  spinner.start();
  geometry_msgs::Pose target_pose;
  std::string name("");
  char flag = 'X';
  try {
    while (ros::ok()) {
      while (true) {
        ROS_INFO_NAMED("pilz_tutorial","将机器人移动到需要记录的位置,输入'Y'确定,'Q'退出");
        std::cin >> flag;
        if(flag == 'Y') {
          break;
        } else if(flag == 'Q') {
          ros::shutdown();
          return 0;
        }
      }
      ROS_INFO_NAMED("pilz_tutorial","输入当前位置的名称,'Q'退出");
      std::cin >> name;
      if (name == "Q") {
        ros::shutdown();
        return 0;
      } else {
        std::vector<double> joints =
            ur5e.move_group_ptr_->getCurrentJointValues();
        std::string file_root = ros::package::getPath("pilz_tutorial") + "/data/";
        writeFile(file_root + "robot.json", name, joints);
      }
    }
  } catch (robot_exception &e) {
    std::cerr << e.get_exception() << '\n';
  }
}
